package plugin

import (
	"context"
	"fmt"
	"github.com/tencentyun/cos-go-sdk-v5"
	"likeadmin/util"
	"mime/multipart"
	"net/http"
	"net/url"
	"path"
)

var QCloudCos = qcloudCos{}

type qcloudCos struct{}

func (q qcloudCos) initOssClient() (client *cos.Client) {

	conf := util.SettingUtil.GetStorageEngineConf("qcloud")

	u, _ := url.Parse(fmt.Sprintf("https://%s.cos.%s.myqcloud.com", conf.Bucket, conf.Region))
	// 用于 Get Service 查询，默认全地域 service.cos.myqcloud.com
	su, _ := url.Parse(fmt.Sprintf("https://cos.%s.myqcloud.com", conf.Region))
	b := &cos.BaseURL{BucketURL: u, ServiceURL: su}
	// 1.永久密钥
	client = cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  conf.AccessKey,
			SecretKey: conf.SecretKey,
		},
	})

	return
}

func (q qcloudCos) Upload(file *multipart.FileHeader, key string, folder string) (err error) {
	c := q.initOssClient()

	objectName := path.Join(folder, key)

	// 读取文件流
	src, err := file.Open()
	if err != nil {
		return
	}
	defer src.Close()

	_, err = c.Object.Put(context.Background(), objectName, src, nil)

	return
}

func (q qcloudCos) Delete(objectName string) (err error) {
	c := q.initOssClient()
	_, err = c.Object.Delete(context.Background(), objectName)

	return
}
